package com.tsdykj.peng.diary.function;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.tsdykj.peng.diary.MainActivity;
import com.tsdykj.peng.diary.R;
import com.tsdykj.peng.diary.bean.UpdateInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static android.support.v4.app.ActivityCompat.startActivity;

/**
 * Created by peng on 2015/4/22.
 */
public class PUtils {

    public static void InstallApk(Activity activity, File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(activity, intent, null);
    }

    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Log.d("LOCAL VERSION: ", packInfo.versionName);
        return packInfo.versionName;
    }

    public static void ShowUpdataDialog(final Context context, final UpdateInfo info) {
        AlertDialog.Builder builer = new AlertDialog.Builder(context);
        builer.setTitle(context.getString(R.string.version_upt));
        builer.setMessage(info.getDescription());
        builer.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                new DownloadTask((Activity) context).execute(info);
            }
        });
        builer.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

    public static void CheckUpdate(final Context context) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        String url = PathManager.Host + "update/check";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    UpdateInfo updateInfo = new UpdateInfo();
                    updateInfo.setVersion(response.getString("version"));
                    updateInfo.setDescription(response.getString("description"));

                    if (!PUtils.getVersionName(context).equals(updateInfo.getVersion())) {
                        Log.d("CHECKVERSION", "found new version on server");
                        PUtils.ShowUpdataDialog(context, updateInfo);
                    } else {
//                        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
//                        alertDialog.setMessage(context.getString(R.string.already_last_version));
                    }
                } catch (JSONException jsonerr) {
                    jsonerr.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toast.makeText(context, context.getString(R.string.network_err), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("version", PUtils.getVersionName(context));
                return map;
            }
        };

        requestQueue.add(request);
    }

    public static void SetReminder(Context context, String user_id) {

        Intent intent = new Intent(context, DiaryReminderReceiver.class);
        intent.putExtra("user_id", user_id);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.MINUTE, 20);
        calendar.set(Calendar.HOUR_OF_DAY, 17);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    public static void CancelReminder(Context context) {

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, DiaryReminderReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        alarmManager.cancel(pendingIntent);
    }

    public static void ShowNotification(Context context,String user_id) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("user_id", user_id);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new Notification();
        notification.icon = R.drawable._edit;
        notification.tickerText = "Job Diary Reminder";
        notification.defaults = Notification.DEFAULT_ALL;
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.when = System.currentTimeMillis();

        notification.setLatestEventInfo(context,context.getString(R.string.app_name) , context.getString(R.string.diary_reminder_tip), pendingIntent);
        notificationManager.notify(0, notification);
    }

    public static boolean getTodayMailed(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences("day_mail", context.MODE_PRIVATE);
        return sharedPreferences.getBoolean("already_mailed", false);
    }

    public static void setTodayMailed(Context context, Boolean mailed){
        SharedPreferences sharedPreferences = context.getSharedPreferences("day_mail", context.MODE_PRIVATE);
        sharedPreferences.edit().putBoolean("already_mailed", mailed).commit();
    }

}
